package org.csu.mypetstore.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.mypetstore.api.common.CommonResponse;
import org.csu.mypetstore.api.entity.*;
import org.csu.mypetstore.api.persistence.*;
import org.csu.mypetstore.api.service.CartService;
import org.csu.mypetstore.api.service.CatalogService;
import org.csu.mypetstore.api.service.OrderService;
import org.csu.mypetstore.api.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service("OrderService")
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SequenceMapper sequenceMapper;
    @Autowired
    private OrderStatusMapper orderStatusMapper;
    @Autowired
    private CartItemMapper cartItemMapper;
    @Autowired
    private LineitemMapper lineitemMapper;
    @Autowired
    private  ItemMapper itemMapper;
    @Autowired
    private CatalogService catalogService;
    @Autowired
    private CartService cartService;

    //***************订单模块***************//
    //初始化订单
    public CommonResponse initOrder(AccountVO accountVO){
        Orders order=new Orders();
        order.setUsername(accountVO.getUsername());
        order.setOrderDate(new Date());
        order.setShipToFirstName(accountVO.getFirstName());
        order.setShipToLastName(accountVO.getLastName());
        order.setShipAddress1(accountVO.getAddress1());
         order.setShipAddress2(accountVO.getAddress2());
         order.setShipCity(  accountVO.getCity());
         order.setShipState(  accountVO.getState());
         order.setShipZip(  accountVO.getZip());
         order.setShipCountry(  accountVO.getCountry());
         order.setBillToFirstName(  accountVO.getFirstName());
         order.setBillToLastName(  accountVO.getLastName());
         order.setBillAddress1  (accountVO.getAddress1());
         order.setBillAddress2 ( accountVO.getAddress2());
         order.setBillCity ( accountVO.getCity());
         order.setBillState ( accountVO.getState());
         order.setBillZip ( accountVO.getZip());
         order.setBillCountry ( accountVO.getCountry());
         order.setCreditCard("999 9999 9999 9999") ;
        order.setExpiryDate ( "12/03");
         order.setCardType  ("Visa");
         order.setCourier(  "UPS");
        order.setLocale  ("CA");
        OrderStatus orderStatus=new OrderStatus();
        orderStatus.setStatus(  "I");

        List<CartVO> cartVOList=new ArrayList<>();
        cartVOList= (List<CartVO>) cartService.getCartItemsByUsername(accountVO.getUsername());

        BigDecimal total= BigDecimal.valueOf(0);
        for(int i=0;i<cartVOList.size();i++){
            total = total.add(cartVOList.get(i).getTotalprice());
        }
        order.setTotalPrice (total);

        List<LineItem> lineItems=new ArrayList<>();
        cartVOTOLineItems(cartVOList,lineItems);
        List<LineItemVO> lineItemVOS=new ArrayList<>();
        for (int i=0;i<lineItems.size();i++){
            CommonResponse<ItemVO> response=catalogService.getItemByItemId(lineItems.get(i).getItemId());
            lineItemVOS.add(entityTOLineItemVO(response,lineItems.get(i)));
        }

        OrderVO orderVO=new OrderVO();
        orderVO=entityToVO(order,orderStatus, lineItemVOS);
        return CommonResponse.createForSuccess(orderVO);
    }
    public void cartVOTOLineItems(List<CartVO> cartVOList,List<LineItem> lineItems){
        LineItem lineItem = new LineItem();
        for (int i=0;i<cartVOList.size();i++){
            lineItem.setItemId(cartVOList.get(i).getItemId());
            lineItem.setLineNum(lineItems.size()+1);
            lineItem.setUnitPrice(itemMapper.selectById(cartVOList.get(i).getItemId()).getListPrice());
            lineItem.setQuantity(cartVOList.get(i).getQuantity());
        }
        lineItems.add(lineItem);
    }

//    //获取所有orders
//    public CommonResponse<List<Orders>> getOrderList(){
//        List<Orders> ordersList=orderMapper.selectList(null);
//        try{
//            if(ordersList.isEmpty()){
//                return CommonResponse.createForSuccessMessage("目前还没有任何订单");
//            }
//            return CommonResponse.createForSuccess(ordersList);
//        } catch (Exception e) {
//            System.out.println("orders查询出错"+ e);
//            return CommonResponse.createForError("orders查询出错");
//        }
//    }

    //获取所有orders by username
    public CommonResponse<List<Orders>> getOrderListbyUsername(String username){
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("userid ",username);
        List<Orders> ordersList=orderMapper.selectList(queryWrapper);
        if(ordersList.isEmpty()){
            return CommonResponse.createForSuccessMessage("目前还没有任何订单");
        }
        return CommonResponse.createForSuccess(ordersList);
    }

    //由orderid获取单个order信息
    public CommonResponse<OrderVO> getOrderByOrderId(Integer orderId){
        try {
            Orders order = orderMapper.selectById(orderId);
            OrderStatus orderStatus=orderStatusMapper.selectById(orderId);
            List<LineItemVO> lineItemsVO=lineItemsTOLineItemVO(orderId);
            OrderVO orderVO=entityToVO(order,orderStatus,lineItemsVO);
            if (orderVO == null) {
                return CommonResponse.createForSuccessMessage("没有该订单的信息");
            }
            return CommonResponse.createForSuccess(orderVO);
        } catch (Exception e) {
            System.out.println("order查询出错"+ e);
            return CommonResponse.createForError("order查询出错");
        }
    }

    //生成订单
    public CommonResponse insertOrder(OrderVO orderVO){
        try{
            Sequence sequence = new Sequence();
            QueryWrapper<Sequence> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("name","ordernum");
            sequence.setNextId(sequence.getNextId()+1);
            sequenceMapper.updateById(sequence);

            orderVO.setOrderId(sequence.getNextId());
            Orders order=orderVOTOOrder(orderVO);
            OrderStatus orderStatus=orderVOTOOrderStatus(orderVO);
            List<LineItem> lineItems=orderVOTOLineItems(orderVO);
            orderMapper.insert(order);
            orderStatusMapper.insert(orderStatus);
            for (int i = 0; i < lineItems.size(); i++) {
                lineitemMapper.insert(lineItems.get(i));
            }
            List<LineItemVO> lineItemVOS=lineItemsTOLineItemVO(orderVO.getOrderId());
            OrderVO newOrderVO=entityToVO(order,orderStatus,lineItemVOS);

            return CommonResponse.createForSuccess("订单生成成功！",newOrderVO);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.createForError("订单生成失败！");
        }
    }

    private OrderVO entityToVO(Orders order, OrderStatus orderStatus,List<LineItemVO> lineItems) {
        OrderVO orderVO=new OrderVO();
        orderVO.setOrderDate(order.getOrderDate());
        orderVO.setOrderId(order.getOrderId());
        orderVO.setUsername(order.getUsername());
        orderVO.setBillAddress1(order.getBillAddress1());
        orderVO.setBillAddress2(order.getBillAddress2());
        orderVO.setBillCity(order.getBillCity());
        orderVO.setBillCountry(order.getBillCountry());
        orderVO.setBillState(order.getBillState());
        orderVO.setBillToFirstName(order.getBillToFirstName());
        orderVO.setBillToLastName(order.getBillToLastName());
        orderVO.setBillZip(order.getBillZip());
        orderVO.setCardType(order.getCardType());
        orderVO.setCourier(order.getCourier());
        orderVO.setCreditCard(order.getCreditCard());
        orderVO.setExpiryDate(order.getExpiryDate());
        orderVO.setTotalPrice(order.getTotalPrice());
        orderVO.setShipZip(order.getShipZip());
        orderVO.setShipToLastName(order.getShipToLastName());
        orderVO.setShipToLastName(order.getShipToLastName());
        orderVO.setShipAddress1(order.getShipAddress1());
        orderVO.setShipAddress2(order.getShipAddress2());
        orderVO.setShipCity(order.getShipCity());
        orderVO.setShipCountry(order.getShipCountry());
        orderVO.setShipState(order.getShipState());
        orderVO.setLocale(order.getLocale());

        //OrderStatus Table
        orderVO.setStatus(orderStatus.getStatus());

        //LineItem Table
        orderVO.setLineItems(lineItems);

        return orderVO;
    }

    private OrderStatus orderVOTOOrderStatus(OrderVO orderVO) {
        OrderStatus orderStatus=new OrderStatus();
        orderStatus.setOrderId(orderVO.getOrderId());
        orderStatus.setStatus(orderVO.getStatus());
        orderStatus.setLineNum(orderVO.getOrderId());
        orderStatus.setTimestamp(orderVO.getOrderDate());
        return orderStatus;
    }

    private Orders orderVOTOOrder(OrderVO orderVO) {
        Orders order=new Orders();
        order.setOrderDate(orderVO.getOrderDate());
        order.setOrderId(orderVO.getOrderId());
        order.setUsername(orderVO.getUsername());
        order.setBillAddress1(orderVO.getBillAddress1());
        order.setBillAddress2(orderVO.getBillAddress2());
        order.setBillCity(orderVO.getBillCity());
        order.setBillCountry(orderVO.getBillCountry());
        order.setBillState(orderVO.getBillState());
        order.setBillToFirstName(orderVO.getBillToFirstName());
        order.setBillToLastName(orderVO.getBillToLastName());
        order.setBillZip(orderVO.getBillZip());
        order.setCardType(orderVO.getCardType());
        order.setCourier(orderVO.getCourier());
        order.setCreditCard(orderVO.getCreditCard());
        order.setExpiryDate(orderVO.getExpiryDate());
        order.setTotalPrice(orderVO.getTotalPrice());
        order.setShipZip(orderVO.getShipZip());
        order.setShipToLastName(orderVO.getShipToLastName());
        order.setShipToLastName(orderVO.getShipToLastName());
        order.setShipAddress1(orderVO.getShipAddress1());
        order.setShipAddress2(orderVO.getShipAddress2());
        order.setShipCity(orderVO.getShipCity());
        order.setShipCountry(orderVO.getShipCountry());
        order.setShipState(orderVO.getShipState());
        order.setLocale(orderVO.getLocale());
        return order;
    }

    private List<LineItem> orderVOTOLineItems (OrderVO orderVO){
        List<LineItemVO> lineItemVOS=new ArrayList<>();
        lineItemVOS=orderVO.getLineItems();
        List<LineItem> lineItems=new ArrayList<>();
        for(int i=0;i<lineItemVOS.size();i++){
            LineItem lineItem=new LineItem();
            lineItem.setItemId(lineItemVOS.get(i).getItemId());
            lineItem.setLineNum(lineItemVOS.get(i).getLineNum());
            lineItem.setOrderId(orderVO.getOrderId());
            lineItem.setQuantity(lineItemVOS.get(i).getQuantity());
            lineItem.setUnitPrice(lineItemVOS.get(i).getUnitPrice());
            lineItems.add(lineItem);
        }
        return lineItems;
    }

    private List<LineItemVO> lineItemsTOLineItemVO(Integer orderId) {
        List<LineItem> lineItems=new ArrayList<>();
        QueryWrapper<LineItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("orderid ",orderId);
        lineItems=lineitemMapper.selectList(queryWrapper);
        List<LineItemVO> lineItemsVO=new ArrayList<>();
        for (int i=0;i<lineItems.size();i++){
            CommonResponse<ItemVO> response=catalogService.getItemByItemId(lineItems.get(i).getItemId());
            lineItemsVO.add(entityTOLineItemVO(response,lineItems.get(i)));
        }
        return lineItemsVO;
    }

    private LineItemVO entityTOLineItemVO(CommonResponse<ItemVO> response,LineItem lineItem){
        LineItemVO lineItemVO=new LineItemVO();
        lineItemVO.setItemId(lineItem.getItemId());
        lineItemVO.setLineNum(lineItem.getLineNum());
        lineItemVO.setOrderId(lineItem.getOrderId());
        lineItemVO.setQuantity(lineItem.getQuantity());
        lineItemVO.setUnitPrice(lineItem.getUnitPrice());
        lineItemVO.setAttribute1(response.getData().getAttribute1());
        lineItemVO.setAttribute2(response.getData().getAttribute2());
        lineItemVO.setAttribute3(response.getData().getAttribute3());
        lineItemVO.setAttribute4(response.getData().getAttribute4());
        lineItemVO.setAttribute5(response.getData().getAttribute5());
        lineItemVO.setProductName(response.getData().getProductName());
        return lineItemVO;
    }

//    //查看未发货订单
//    public CommonResponse<List<OrderStatus>> getUndeliveredOrder(){
//        QueryWrapper<OrderStatus> queryWrapper = new QueryWrapper<>();
//        queryWrapper.like("status","I");
//        List<OrderStatus> ordersList=orderStatusMapper.selectList(queryWrapper);
//        if(ordersList.isEmpty()){
//            return CommonResponse.createForSuccessMessage("目前没有未发货订单");
//        }
//        return CommonResponse.createForSuccess(ordersList);
//    }
//
//    //查看已发货订单
//    public CommonResponse<List<OrderStatus>> getDeliveredOrder(){
//        QueryWrapper<OrderStatus> queryWrapper = new QueryWrapper<>();
//        queryWrapper.like("status","P");
//        List<OrderStatus> ordersList=orderStatusMapper.selectList(queryWrapper);
//        if(ordersList.isEmpty()){
//            return CommonResponse.createForSuccessMessage("目前没有已发货订单");
//        }
//        return CommonResponse.createForSuccess(ordersList);
//    }
//
//    //未发货订单发货
//    public CommonResponse Deliver(Integer orderId){
//        try {
//            OrderStatus orderStatus = orderStatusMapper.selectById(orderId);
//            orderStatus.setStatus("P");
//            orderStatusMapper.updateById(orderStatus);
//            return CommonResponse.createForSuccess("已发货");
//        }
//        catch (Exception e) {
//            e.printStackTrace();
//            return CommonResponse.createForError("订单发货失败！");
//        }
//    }
//
//    //修改用户订单
//    public CommonResponse editOrder(OrderVO orderVO){
//        try {
//            Orders order=orderVOTOOrder(orderVO);
//            OrderStatus orderStatus=orderVOTOOrderStatus(orderVO);
//            orderMapper.updateById(order);
//            orderStatusMapper.updateById(orderStatus);
//            OrderVO newOrderVO=entityToVO(order,orderStatus);
//            return CommonResponse.createForSuccess("订单修改成功！",newOrderVO);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return CommonResponse.createForError("订单修改失败！");
//        }
//    }
//
//    //搜索订单（by id or username）
//    public CommonResponse<List<Orders>> searchOrder(String keyword){
//        try {
//            QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
//            queryWrapper.like(
//                    "orderId", keyword.toLowerCase()).or().like(
//                            "username",keyword.toLowerCase());
//            List<Orders> orderList = orderMapper.selectList(queryWrapper);
//            if(orderList.isEmpty()) {
//                return CommonResponse.createForSuccessMessage("该关键字下无查询结果");
//            }
//            return CommonResponse.createForSuccess(orderList);
//        } catch (Exception e) {
//            System.out.println("order查询出错"+ e);
//            return CommonResponse.createForError("order查询出错");
//        }
//    }
}
